package com.example.sxy.saxdemo;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.List;

/**
 * Created by SXY on 2015/12/29.
 */
public class SaxHandler extends DefaultHandler {
    private List<Entity> list;
    private Entity entity;
    private String content;

    /**
     * 构造函数
     */
    public SaxHandler(List<Entity> list) {
        this.list = list;
    }

    /**
     * 解析文档开始
     *
     * @throws SAXException
     */
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }
    /**
     * 当SAX解析器解析到某个属性值时，会调用的方法
     * 其中参数ch记录了这个属性值的内容
     */
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
//        保存这个属性值
        content = new String(ch, start, length);
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if ("entity".equals(localName)) {
            entity = new Entity();
        }
    }

    /**
     * 结束标签时调用的函数
     * @param uri
     * @param localName
     * @param qName
     * @throws SAXException
     */
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if ("name".equals(localName)) {
            entity.setName(content);
        } else if ("age".equals(localName)) {
            entity.setAge(content);
        } else if ("entity".equals(localName)) {
            list.add(entity); //将对象加入到List中
        }
    }
}
